<template>
    <view class="add-container">
        <!-- 拍照上传区域 -->
        <view class="photo-section">
            <view class="photo-box" @click="takePhoto" v-if="!tempFilePath">
                <uni-icons type="camera" size="40" color="#999"></uni-icons>
                <text class="photo-tip">点击拍照</text>
            </view>
            <image v-else :src="tempFilePath" mode="aspectFill" class="preview-image"></image>
        </view>
        
        <!-- 药品信息编辑区域 -->
        <view class="form-section">
            <view class="form-item">
                <text class="label">药品名称</text>
                <input type="text" v-model="medicineInfo.drugName" placeholder="请输入药品名称" />
            </view>
            
            <view class="form-item">
                <text class="label">药品剂量</text>
                <picker mode="selector" :range="dosageOptions" :value="dosageIndex" @change="onDosageChange">
                    <view class="picker-value">{{ medicineInfo.drugDosage || '请选择药品剂量' }}</view>
                </picker>
            </view>
            
            <view class="form-item">
                <text class="label">服用频率</text>
                <picker mode="selector" :range="frequencyOptions" :value="frequencyIndex" @change="onFrequencyChange">
                    <view class="picker-value">{{ medicineInfo.frequency || '请选择服用频率' }}</view>
                </picker>
            </view>
            
            <view class="form-item">
                <text class="label">生产日期</text>
                <picker mode="date" :value="medicineInfo.productionTime" @change="onProductionDateChange" @focus="showDatePicker">
                    <view class="picker-value">{{ truncateAlarmTime( medicineInfo.productionTime) || '请选择生产日期' }}</view>
                </picker>
            </view>
            
            <view class="form-item">
                <text class="label">过期日期</text>
                <picker mode="date" :value="medicineInfo.uselessTime" @change="onExpiryDateChange" @focus="showDatePicker">
                    <view class="picker-value">{{ truncateAlarmTime(medicineInfo.uselessTime)  || '请选择过期日期' }}</view>
                </picker>
            </view>
            
            <view class="form-item">
                <text class="label">自定义剂量</text>
                <input type="text" v-model="medicineInfo.customDosage" placeholder="例如：每次2片" />
            </view>
        </view>
        
        <!-- 保存按钮 -->
        <button class="save-btn" type="primary" @click="saveMedicine" style="background-color: #8bdee6;">保存</button>
    </view>
</template>

<script>
import { useMedicineStore } from '../../store/medicine';
import { useUserStore } from '../../store/user';
import { uploadImage, addMedicine } from '@/api/medicineHttp'

import constants from '../../utils/constants';
const medicineStore = useMedicineStore()
const userStore = useUserStore

// 日期格式化函数
function formatDate(date) {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export default {
    setup(){
        return{
            medicineStore,
            userStore
        }
    },
    data() {
        return {
            tempFilePath: '', // 临时图片路径
            medicineInfo: {
                drugName: '',
                drugDosage: '',
                frequency: '',
                productionTime: '',
                uselessTime: '',
                customDosage: ''
            },
            dosageOptions: ['1片', '2片', '3片', '4片', '5片'], // 药品剂量选项
            dosageIndex: 0, // 药品剂量选项索引
            frequencyOptions: ['每天1次', '每天2次', '每天3次', '饭后服用', '饭前服用'], // 服用频率选项
            frequencyIndex: 0 // 服用频率选项索引
        }
    },

    onLoad(){
    },
    methods: {
      truncateAlarmTime(time) {
          // 这里假设截取前3个字符，你可以根据实际需求修改截取的位置
          return time ? time.substring(0, 10) : '';
      },
        // 拍照
        takePhoto() {
            uni.chooseImage({
                count: 1,
                sourceType: ['camera'],
                success: (res) => {
                    this.tempFilePath = res.tempFilePaths[0];
                }
            });
        },
        // 药品剂量选择
        onDosageChange(e) {
            this.dosageIndex = e.detail.value;
            this.medicineInfo.drugDosage = this.dosageOptions[this.dosageIndex];
        },
        // 服用频率选择
        onFrequencyChange(e) {
            this.frequencyIndex = e.detail.value;
            this.medicineInfo.frequency = this.frequencyOptions[this.frequencyIndex];
        },
        // 生产日期选择
        onProductionDateChange(e) {
            // 格式化日期
            this.medicineInfo.productionTime = formatDate(e.detail.value);
        },
        // 过期日期选择
        onExpiryDateChange(e) {
            // 格式化日期
            this.medicineInfo.uselessTime = formatDate(e.detail.value);
        },
        // 上传图片
        // 上传图片
        
        // 保存药品信息
        async saveMedicine() {
            if (!this.tempFilePath) {
                uni.showToast({
                    title: '请先拍照上传药品图片',
                    icon: 'none'
                });
                return;
            }
            if (!this.medicineInfo.drugName) {
                uni.showToast({
                    title: '请输入药品名称',
                    icon: 'none'
                });
                return;
            }
            if (!this.medicineInfo.drugDosage) {
                uni.showToast({
                    title: '请选择药品剂量',
                    icon: 'none'
                });
                return;
            }

            uni.showModal({
                title: '保存成功',
                content: '返回主页下拉刷新列表',
                showCancel: false,
                success() {
                  uni.switchTab({
                    url:'/pages/home/home'
                  })
                }
            });

            try {
                // 先上传图片
                const imageResult = await uploadImage(this.tempFilePath)
                
                // 构建完整的药品信息
                const medicineData = {
                    ...this.medicineInfo,
                    picture: JSON.parse(imageResult).data, // 这里假设后端返回图片URL
                };
                

                await addMedicine(medicineData)
                console.log(1);
                // 发送药品信息到后端
                this.tempFilePath = '' // 临时图片路径
                this.medicineInfo.drugName = ''
                this.medicineInfo.drugDosage = ''
                this.medicineInfo.frequency = ''
                this.medicineInfo.productionTime = ''
                this.medicineInfo.uselessTime = ''
                this.medicineInfo.customDosage = ''
                await this.medicineStore.getMedicineList(1)
                setTimeout(()=>{
                  this.medicineStore.medicines
                },1000)
                

            } catch (error) {
                uni.hideLoading();
                uni.showToast({
                    title: '保存失败，请重试',
                    icon: 'none'
                });
                console.error('保存失败：', error);
            }
        },
        // 显示日期选择器
        showDatePicker() {
            // 这里可以添加一些额外的逻辑来确保日期选择器正常显示
        }
    }
}
</script>

<style lang="scss">
.add-container {
    padding: 30rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.photo-section {
    margin-bottom: 40rpx;
    
    .photo-box {
        width: 100%;
        height: 400rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
        
        .photo-tip {
            font-size: 28rpx;
            color: #999;
            margin-top: 20rpx;
        }
    }
    
    .preview-image {
        width: 100%;
        height: 400rpx;
        border-radius: 16rpx;
    }
}

.form-section {
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 40rpx;
    
    .form-item {
        padding: 20rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
            border-bottom: none;
        }
        
        .label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 10rpx;
            display: block;
        }
        
        input {
            height: 60rpx;
            font-size: 28rpx;
            width: 100%;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            padding: 10rpx;
            box-sizing: border-box;
        }
        
        .picker-value {
            height: 60rpx;
            line-height: 60rpx;
            font-size: 28rpx;
            color: #333;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            padding: 0 10rpx;
            box-sizing: border-box;
        }
    }
}

.save-btn {
    width: 90%;
    margin: 0 auto;
    background-color: #2ac2d1;
    color: #fff;
    font-size: 32rpx;
    border-radius: 50rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    
    &::after {
        border: none;
    }
}
</style>